package daemon

import (
	"context"
	log "github.com/sirupsen/logrus"
	"golang.org/x/sync/errgroup"
	"miao-va-host/daemon/miao"
	"time"
)

type Daemon struct {
	exitFunc   context.CancelFunc
	miaoClient *miao.Client
}

func NewDaemon() *Daemon {
	return &Daemon{}
}

// Run runs the service and blocks until complete.
func (a *Daemon) Run(parentCtx context.Context) {
	var (
		g   errgroup.Group
		err error
	)
	ctx, cancelFunc := context.WithCancel(parentCtx)
	a.exitFunc = cancelFunc
	a.miaoClient = miao.InitConnection()

	// 监听va client 消息
	g.Go(func() error {
		for {
			if !a.miaoClient.IsClosed {
				inst, err := a.miaoClient.ReaderMessage()
				if err != nil {
					log.Error("clientConn.ReaderMessage() err : ", err)
					continue
				}
				a.miaoClient.HandMsg(inst)
			}
		}
	})
	// va client 发送ping信号
	g.Go(func() error {
		ticker := time.NewTicker(5 * time.Second) //60
		for range ticker.C {
			a.miaoClient.Ping()
		}
		return nil
	})
	// 优雅的关闭 va client
	g.Go(func() error {
		defer func() {
			cancelFunc()
			log.Debug("优雅关闭 miao server 协程-已退出")
		}()
		<-ctx.Done()
		return nil //nolint
	})

	err = g.Wait()
	if err != nil {
		log.Fatal("shutting down the server")
	}
}
